﻿using System.Net;
using System.Net.Sockets;
using System.Text;

namespace 中间服务器
{
    internal class Program
    {
        //
        static Dictionary<IPEndPoint, string> clients = new Dictionary<IPEndPoint, string>();
        static void Main(string[] args)
        {
            //监听端口
            UdpClient server = new UdpClient(9999);
            Console.WriteLine("Server listening on port 9999");

            while (true)
            {
                IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
                byte[] receiveBuffer = server.Receive(ref remoteEP);
                string message = Encoding.UTF8.GetString(receiveBuffer);

                if (!clients.ContainsKey(remoteEP))
                {
                    clients[remoteEP] = message; // 记录设备信息
                    Console.WriteLine($"Connected: {remoteEP} - {message}");
                }

                // 将设备信息发送给其他设备
                foreach (var client in clients)
                {
                    if (client.Key != remoteEP)
                    {
                        string addressInfo = $"{remoteEP.Address}:{remoteEP.Port}";
                        byte[] sendBuffer = Encoding.UTF8.GetBytes($"ADDRESS_INFO:{addressInfo}");
                        server.Send(sendBuffer, sendBuffer.Length, client.Key);
                    }
                }
            }
        }
    }
}
